import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

# 定义正态分布的参数
mean = 0.1  # 均值为10%
std_dev = 0.015  # 标准差为1.5%

# 定义样本大小
sample_size = 10000

# 进行蒙特卡洛模拟
num_simulations = 10000
all_results = []
for _ in range(num_simulations):
    # 从正态分布中抽取样本
    samples = np.random.normal(mean, std_dev, sample_size)

    # 计算次品率
    defective_rate = np.mean(samples)

    # 将结果添加到列表中
    all_results.append(defective_rate)

# 计算模拟结果的均值和标准差
mean_result = np.mean(all_results)
std_dev_result = np.std(all_results)

print(f"模拟的次品率均值为：{mean_result}")
print(f"模拟的次品率标准差为：{std_dev_result}")

# 使用t分布进行假设检验，比较实际次品率与理论次品率的差异
alpha = 0.05  # 显著性水平
t_statistic, p_value = stats.ttest_1samp(all_results, mean)

if p_value < alpha:
    print("拒绝原假设，即实际次品率与理论次品率有显著差异。")
else:
    print("接受原假设，即实际次品率与理论次品率无显著差异。")

# 绘制实际次品率和理论次品率的直方图
plt.hist(all_results, bins=50, alpha=0.75, label='Actual defective rate')
plt.axvline(x=mean, color='r', linestyle='dashed', linewidth=2, label='Theoretical rejection rate')
plt.xlabel('Defective rate')
plt.ylabel('frequency')
plt.title('Comparison of the actual defective rate with the theoretical defective rate')
plt.legend()
plt.show()
